package com.virtium.vpm.action;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.List;
import java.util.ListIterator;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

import com.virtium.vpm.controller.MajorTaskManager;
import com.virtium.vpm.controller.ProjectManager;
import com.virtium.vpm.controller.TypeManager;
import com.virtium.vpm.controller.UserManager;
import com.virtium.vpm.controller.UserSession;
import com.virtium.vpm.controller.UserSessionManager;
import com.virtium.vpm.form.ProjectForm;
import com.virtium.vpm.form.ProjectRowForm;
import com.virtium.vpm.form.UserForm;
import com.virtium.vpm.hibernate.model.MajorTask;
import com.virtium.vpm.hibernate.model.Project;
import com.virtium.vpm.hibernate.model.Type;
import com.virtium.vpm.hibernate.model.User;
import com.virtium.vpm.json.JSONArray;
import com.virtium.vpm.json.JSONObject;
import com.virtium.vpm.util.DateUtil;
import com.virtium.vpm.util.FormUtil;
import com.virtium.vpm.util.SecurityUtil;
import com.virtium.vpm.util.StringUtil;

/**
 * TuanAnh
 */
public class DoProjectList extends DispatchAction {
	/*
	 * Generated Methods
	 */
	protected ActionForward unspecified(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		System.out
				.println("hahahahahahahhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhhh");
		// String message =messages.getMessage(*"dispatch.parameter"*,
		// mapping.getPath(),mapping.getParameter());
		// log.error(message);
		// return getAllProjectList(mapping,form,request,response);
		return null;
	}

	public ActionForward main(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		ProjectForm projectForm = (ProjectForm) form;
		// FormUtil.setSessionValue(request, "SESSION_USER", user);
		UserSession user = (UserSession) FormUtil.getSessionValue(request,
				"SESSION_USER");
		if (user != null)
			projectForm.setUserSession(user);
		return mapping.findForward("main");
	}

	public ActionForward usermgt(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response) {
		ProjectForm projectForm = (ProjectForm) form;
		// FormUtil.setSessionValue(request, "SESSION_USER", user);
		UserSession user = (UserSession) FormUtil.getSessionValue(request,
				"SESSION_USER");
		if (user != null)
			projectForm.setUserSession(user);
		return mapping.findForward("usermgt");
	}

	/**
	 * Method execute
	 * 
	 * @param mapping
	 * @param form
	 * @param request
	 * @param response
	 * @return ActionForward
	 */
	public ActionForward getAllProjectList(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) {
		try {

			ProjectForm projectForm = (ProjectForm) form;

			JSONArray arrResult = new JSONArray();
			ProjectManager projectManager = new ProjectManager();
			ArrayList<ArrayList> arrAllTables = projectManager
					.getAllListProject(0);
			ArrayList<ArrayList> arrAllProject = projectManager
					.getAllListProject(0).get(0);
			ArrayList<String[]> arrProjectInfo = projectManager
					.getAllListProject(0).get(1);
			JSONArray jsonArray;

			for (int i = 0; i < arrAllProject.size(); i++) {
				ArrayList<ProjectRowForm> arrProjectRowForm = arrAllProject
						.get(i);
				Collections.sort(arrProjectRowForm);
				ListIterator<ProjectRowForm> lt = arrProjectRowForm
						.listIterator();

				jsonArray = new JSONArray();
				while (lt.hasNext()) {
					ProjectRowForm prf = lt.next();
					String archived = prf.getAchieved().endsWith("1") ? "Yes"
							: "No";
					JSONObject jsonObjectTemp = new JSONObject();
					jsonObjectTemp.put("tableId", prf.getTableId());
					jsonObjectTemp.put("majorTaskId", prf.getMajorTaskid());
					jsonObjectTemp.put("TypeID", prf.getTypeID().toString());
					jsonObjectTemp.put("UserID", prf.getUserID().toString());
					jsonObjectTemp.put("Type", prf.getType().toString());
					jsonObjectTemp
							.put("Priority", prf.getPriority().toString());
					jsonObjectTemp.put("MajorTask", prf.getMajorTask()
							.toString());
					jsonObjectTemp.put("Owner", prf.getOwner().toString());
					jsonObjectTemp.put("StartDate", prf.getStartDate()
							.toString());
					jsonObjectTemp.put("FinishDate", prf.getFinishDate()
							.toString());
					jsonObjectTemp.put("Cost", prf.getCost().toString());
					jsonObjectTemp.put("Achieved", archived.toString());
					jsonObjectTemp.put("KeyIssues", prf.getKeyIssues()
							.toString());
					jsonObjectTemp.put("DecisionNeed", prf.getDecisionNeed()
							.toString());
					jsonArray.put(jsonObjectTemp);
				}
				JSONObject jsonProjectInfo = new JSONObject();
				jsonProjectInfo.put("purpose", arrProjectInfo.get(i)[0]);
				jsonProjectInfo.put("ideaOutcome", arrProjectInfo.get(i)[1]);
				jsonProjectInfo.put("email", arrProjectInfo.get(i)[2]);
				jsonProjectInfo.put("archived", arrProjectInfo.get(i)[3]);
				JSONArray jsonArrayInfo = new JSONArray();
				jsonArrayInfo.put(jsonProjectInfo);

				JSONArray jsonArrayTotal = new JSONArray();
				jsonArrayTotal.put(jsonArrayInfo);
				jsonArrayTotal.put(jsonArray);

				arrResult.put(jsonArrayTotal.toString());

			}
			// projectForm.setTextMessage("Hello Nguyễn Tuấn Anh !");
			// projectForm.setProjectList(arrResult);
			response.setContentType("application/xml;charset=UTF-8");
			response.getWriter().write(arrResult.toString());
			response.getWriter().flush();
			response.getWriter().close();
		} catch (Exception ex) {
		}
		// return mapping.findForward("mainPage");
		return null;
	}

	public ActionForward getAllUserAndType(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		JSONArray jarr, jarr1, jarr2;
		try {
			UserManager um = new UserManager();
			ArrayList<User> arrUser = um.getAllUser();

			TypeManager typeManager = new TypeManager();
			ArrayList<Type> lsType = typeManager.getAllTypes();

			jarr1 = new JSONArray();
			for (int i = 0; i < arrUser.size(); i++) {
				JSONObject joTemp = new JSONObject();
				joTemp.put("id", arrUser.get(i).getId().toString());
				joTemp.put("fullName", arrUser.get(i).getFullName().toString());
				joTemp.put("userName", arrUser.get(i).getUserName().toString());
				joTemp.put("password", arrUser.get(i).getPassword().toString());
				jarr1.put(joTemp);
			}

			jarr2 = new JSONArray();
			for (int i = 0; i < lsType.size(); i++) {
				JSONObject temp = new JSONObject();
				temp.put("id", lsType.get(i).getId());
				temp.put("name", lsType.get(i).getName());
				jarr2.put(temp);
			}

			jarr = new JSONArray();
			jarr.put(jarr1);
			jarr.put(jarr2);
			response.setContentType("application/xml;charset=UTF-8");
			response.getWriter().write(jarr.toString());

		} catch (Exception ex) {
		}
		return null;
	}

	public ActionForward getAllEmail(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONArray jarr;
		try {
			ProjectManager pm = new ProjectManager();
			List<Project> lProject = pm.all();

			jarr = new JSONArray();
			ArrayList<String> arrEmail = new ArrayList<String>();

			for (int i = 0; i < lProject.size(); i++) {
				if (!arrEmail.contains(lProject.get(i).getEmail().toString())) {
					arrEmail.add(lProject.get(i).getEmail().toString());
					jarr.put(lProject.get(i).getEmail().toString());
				}
			}
			response.setContentType("application/text");
			response.getWriter().write(jarr.toString());

		} catch (Exception ex) {
		}
		return null;
	}

	// -- ------------------------Major
	// Task------------------------------------//
	public ActionForward addNewMajorTask(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			MajorTaskManager majorTaskManager = new MajorTaskManager();
			int id = majorTaskManager.addNewMajorTask(getParameter(request));
			response.setContentType("application/text");
			response.getWriter().write(id + "");
		} catch (Exception ex) {
		}
		return null;
	}

	public ActionForward updateMajorTask(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		try {
			MajorTaskManager majorTaskManager = new MajorTaskManager();
			majorTaskManager.updateMajorTask(getParameter(request));
			response.setContentType("application/text");
			response.getWriter().write("");
		} catch (Exception ex) {
		}
		return null;
	}

	public ActionForward deleteMajorTask(ActionMapping mapping,
			ActionForm form, HttpServletRequest request,
			HttpServletResponse response) throws Exception {
		String id = request.getParameter("id");

		try {
			MajorTask majorObject = new MajorTask();
			majorObject.setId(Integer.parseInt(id));

			MajorTaskManager majorTaskManager = new MajorTaskManager();
			majorTaskManager.deleteMajorTask(majorObject);

		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write("Ok");
		return null;
	}

	// -- ------------------------Major
	// Task------------------------------------//

	// -- ------------------------Type------------------------------------//
	public ActionForward addType(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String name = request.getParameter("name");

		String id = "";
		try {
			Type type = new Type();
			type.setName(name);

			TypeManager typeManager = new TypeManager();
			id = typeManager.addNewType(type);
		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write(id);
		return null;
	}

	public ActionForward deleteType(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");

		try {
			Type type = new Type();
			type.setId(Integer.parseInt(id));

			TypeManager typeManager = new TypeManager();
			typeManager.delete(type);
		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write("Ok");
		return null;
	}

	public ActionForward getAllType(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONArray jarr;
		try {
			TypeManager typeManager = new TypeManager();
			ArrayList<Type> lsType = typeManager.getAllTypes();
			jarr = new JSONArray();
			ProjectManager pm = new ProjectManager();
			List<Project> arrProject = pm.all();
			for (int i = 0; i < lsType.size(); i++) {
				JSONArray temp = new JSONArray();
				temp.put(lsType.get(i).getName());
				temp.put(pm.countProjectByType(arrProject, lsType.get(i)
						.getId()));
				temp.put(lsType.get(i).getId());
				jarr.put(temp);
			}
			response.setContentType("application/text");
			response.getWriter().write(jarr.toString());

		} catch (Exception ex) {
		}
		return null;
	}

	// -- ------------------------Type------------------------------------//

	// -- ------------------------Project------------------------------------//

	public ActionForward addNewProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			String typeID = request.getParameter("typeID");
			String mail = request.getParameter("email");
			String purpose = request.getParameter("purpose");
			String ideaOutcome = request.getParameter("ideaOutcome");
			Project project = new Project();
			project.setTypeId(Integer.parseInt(typeID));
			project.setEmail(mail);
			project.setArchive("");
			project.setPurpose(purpose);
			project.setIdeaOutcome(ideaOutcome);

			ProjectManager pm = new ProjectManager();
			int newID = pm.addNew(project);

			MajorTaskManager majorTaskManager = new MajorTaskManager();
			MajorTask majorTask = getParameter(request);
			majorTask.setProjectId(newID);
			majorTaskManager.addNewMajorTask(majorTask);

		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write("");
		return null;
	}

	public ActionForward deleteProject(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");

		try {
			Project project = new Project();
			project.setId(Integer.parseInt(id));

			ProjectManager projectManager = new ProjectManager();
			projectManager.delete(project);
		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write("");
		return null;
	}

	// -- ------------------------Project------------------------------------//

	// -- ------------------------User------------------------------------//
	public ActionForward addNewUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		try {
			String fullName = request.getParameter("fullName");
			String userName = request.getParameter("userName");
			String password = request.getParameter("password");
			User user = new User();
			user.setFullName(fullName);
			user.setUserName(userName);
			user.setPassword(SecurityUtil.hashPasswordMD5(password));

			UserManager um = new UserManager();
			String id = um.addNew(user);

			response.setContentType("application/text");
			response.getWriter().write(id + ":" + user.getPassword());
		} catch (Exception ex) {
		}
		return null;
	}

	public ActionForward deleteUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String id = request.getParameter("id");

		try {
			User user = new User();
			user.setId(Integer.parseInt(id));
			UserManager um = new UserManager();
			um.delete(user);

		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write("Ok");
		return null;
	}

	public ActionForward getAllUser(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		JSONArray jarr;
		try {
			UserManager um = new UserManager();
			ArrayList<User> arrUser = um.getAllUser();
			jarr = new JSONArray();
			for (int i = 0; i < arrUser.size(); i++) {
				JSONObject joTemp = new JSONObject();
				joTemp.put("id", arrUser.get(i).getId().toString());
				joTemp.put("fullName", arrUser.get(i).getFullName().toString());
				joTemp.put("userName", arrUser.get(i).getUserName().toString());
				joTemp.put("password", arrUser.get(i).getPassword().toString());
				jarr.put(joTemp);
			}
			response.setContentType("application/text");
			response.getWriter().write(jarr.toString());

		} catch (Exception ex) {
		}
		return null;
	}

	public ActionForward login(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {
		String userName = request.getParameter("u");
		String password = request.getParameter("p");
		String flag = "failue";
		try {
			HttpSession session = request.getSession();
			FormUtil.clearAllSessionAttributes(session);
			UserSession user;
			UserSessionManager sessionMgr = new UserSessionManager();
			if (!StringUtil.isEmpty(userName) && !StringUtil.isEmpty(password)) {
				user = new UserSession();
				user = sessionMgr.authenticateUser(userName, password, session,
						request);
				if (user != null) {
					FormUtil.setSessionValue(request, "SESSION_USER", user);
					flag = "success";
				}
			}

		} catch (Exception ex) {
		}
		response.setContentType("application/text");
		response.getWriter().write(flag);

		return null;
	}

	public ActionForward logout(ActionMapping mapping, ActionForm form,
			HttpServletRequest request, HttpServletResponse response)
			throws Exception {

		try {
			ProjectForm projectForm = (ProjectForm) form;
			projectForm.setUserSession(null);
			HttpSession session = request.getSession();
			FormUtil.clearAllSessionAttributes(session);

		} catch (Exception ex) {
		}

		return mapping.findForward("main");
	}

	// -- ------------------------User------------------------------------//
	private MajorTask getParameter(HttpServletRequest request) {
		String temp = "";

		// ------ Cost --------------------//
		Double cost = 0.0;
		temp = request.getParameter("cost");
		if (temp != null && !temp.trim().equals("")) {
			temp = temp.replace("$", "");
			if (temp.indexOf(".") >= 0)
				temp = temp.substring(0, temp.indexOf("."));
			temp = temp.replaceAll(",", "");
			cost = Double.parseDouble(temp);
		}
		// ------ Cost --------------------//

		// ------ majorTask --------------------//
		String majorTask = request.getParameter("majorTask");
		if (majorTask != null && !majorTask.trim().equals(""))
			majorTask = majorTask.toString();
		else
			majorTask = "";
		// ------ majorTask --------------------//

		// ------ keyIssues --------------------//
		String keyIssues = request.getParameter("keyIssues");
		if (keyIssues != null && !keyIssues.trim().equals(""))
			keyIssues = keyIssues.toString();
		else
			keyIssues = "";
		// ------ keyIssues --------------------//

		// ------ userID --------------------//
		int userID = 0;
		temp = "";
		temp = request.getParameter("userID");
		if (temp != null && !temp.trim().equals("")) {
			try {
				temp = temp.toString();
				userID = Integer.parseInt(temp);
			} catch (Exception ex) {
			}
		}
		// ------ userID --------------------//

		// ------ achived --------------------//
		int achived = 0;
		temp = "";
		temp = request.getParameter("achived");
		if (temp != null && !temp.trim().equals("")) {
			try {
				temp = temp.toString();
				if (temp.equals("Yes"))
					achived = 1;
				else
					achived = 0;
			} catch (Exception ex) {
			}
		}
		// ------ achived --------------------//

		// ------ priority --------------------//
		int priority = 0;
		temp = "";
		temp = request.getParameter("priority");
		if (temp != null && !temp.trim().equals("")) {
			try {
				priority = Integer.parseInt(temp);
			} catch (Exception ex) {
			}
		}
		// ------ priority --------------------//

		// ------ startDate --------------------//
		Date startDate = new Date();
		temp = "";
		temp = request.getParameter("startDate");
		if (temp != null && !temp.trim().equals(""))
			startDate = DateUtil.convertDate(temp, "MM/dd/yyyy");
		// ------ startDate --------------------//

		// ------ finishDate --------------------//
		Date finishDate = new Date();
		temp = "";
		temp = request.getParameter("finishDate");
		if (temp != null && !temp.trim().equals(""))
			finishDate = DateUtil.convertDate(temp, "MM/dd/yyyy");
		// ------ finishDate --------------------//

		// ------ decision --------------------//
		String decision = request.getParameter("decision");
		if (decision != null && !decision.trim().equals(""))
			decision = decision.toString();
		else
			decision = "";
		// ------ decision --------------------//

		// ------ projectID --------------------//
		int projectID = 0;
		temp = "";
		temp = request.getParameter("projectID");
		if (temp != null && !temp.trim().equals("")) {
			try {
				temp = temp.toString();
				projectID = Integer.parseInt(temp);
			} catch (Exception ex) {
			}
		}
		// ------ projectID --------------------//

		// ------ id --------------------//
		int id = -1;
		temp = "";
		temp = request.getParameter("majorTaskId");
		if (temp != null && !temp.trim().equals("")) {
			try {
				temp = temp.toString();
				id = Integer.parseInt(temp);
			} catch (Exception ex) {
			}
		}
		// ------ id --------------------//
		try {
			MajorTask majorObject = new MajorTask();
			if (id != -1)
				majorObject.setId(id);
			majorObject.setProjectId(projectID);
			majorObject.setMajorTask(majorTask.toString());
			majorObject.setUserId(userID);
			majorObject.setPriority(priority);
			majorObject.setStartDate(startDate);
			majorObject.setFinishDate(finishDate);
			majorObject.setCost(cost);
			majorObject.setAchieved(achived);
			majorObject.setKeyIssue(keyIssues.toString());
			majorObject.setDecision(decision.toString());
			return majorObject;

		} catch (Exception ex) {
		}
		return null;
	}

}